<script setup lang="ts">
import MsgBox from '/@/views/chat/components/ChatBox/MsgBox.vue'
import MemberUser from '/src/views/chat/components/ChatBox/MemberUser.vue'
import Session from '/@/views/chat/components/ChatBox/Session.vue'
import { RoomTypeEnum } from '/@/utils/enum'
import { useUserFriendStore, useUserStore, useWebSocketStore } from '/@/store'
import { storeToRefs } from 'pinia'
import socketUtils from '/@/utils/websocket'
import { ElMessage } from 'element-plus'
import { onMounted } from 'vue'

const webSocketStore = useWebSocketStore()
const userStore = useUserStore()
const { currentMemberList, currentContact, currentAllMessageList } =
  storeToRefs(webSocketStore)
const userFriendStore = useUserFriendStore()

onMounted(async () => {
  console.log('onMounted开始加载聊天信息')
  loadData()
})
// 加载数据
const loadData = () => {
  if (!userStore.isSign) {
    ElMessage.error('请先登录')
    return
  }

  // 开始进行websocket链接
  console.log('开始进行websocket链接')
  socketUtils.initConnect()
  // 开始更新用户信息
  userFriendStore.updateUserFriend()
  userFriendStore.updateUserApply({ pageSize: 10, pageNum: 1 })
  userFriendStore.updateAllUser({ pageSize: 10, pageNum: 1 })
  userFriendStore.updateChatGroup()

  userFriendStore.updateContact({ pageSize: 100, pageNum: 1 }).then(r => {
    console.log('更新了updateContact' + r)
    if (r > 0) {
      // 默认选择第一个会话
      if (
        userFriendStore.contact.size !== undefined &&
        userFriendStore.contact.size > 0 &&
        userFriendStore.contactList !== undefined
      ) {
        // 说明成功更新了会话
        const contactVo = userFriendStore.contactList[0]
        if (contactVo.roomId !== undefined) {
          webSocketStore.currentRoomId = contactVo.roomId
        }
        webSocketStore.currentContact = contactVo
      }
    }
  })
}

watch(
  () => userStore.isSign,
  (newValue, oldValue) => {
    loadData()
  },
)
watch(
  () => webSocketStore.currentRoomId,
  (newValue, oldValue) => {
    webSocketStore.updateCurrentRoomId() // 当切换新的房间时。需要进行更新
  },
)
</script>

<template>
  <div class="chat-outer">
    <el-row :gutter="5" class="contain">
      <el-col :span="4">
        <!--              展示用户聊天框-->
        <Session></Session>
      </el-col>
      <el-col :span="20">
        <el-row v-if="webSocketStore.type === RoomTypeEnum.Group" class="msg">
          <el-col :span="20">
            <MsgBox></MsgBox>
          </el-col>
          <el-col :span="4">
            <MemberUser></MemberUser>
          </el-col>
        </el-row>
        <el-row v-else class="msg">
          <el-col :span="24">
            <MsgBox></MsgBox>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.chat-outer {
  width: 100%;
}

.msg {
  width: 100%;
}

.contain {
  width: 100%;
}
</style>
